package com.chinasoft.back.controller;

import com.chinasoft.back.pojo.Article;
import com.chinasoft.back.pojo.Result;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

/**
 * @author 中软zhang
 * @create 2023-08-29 14:45
 */
@RestController
@CrossOrigin
@RequestMapping("my/article")
public class ArticleController {


    @PostMapping("add")
    public Result<String> publishArticle(HttpServletRequest request,
            Article art, MultipartFile cover_img) throws Exception {
        String realPath = request.getSession().getServletContext().getRealPath("/");
        System.out.println(realPath);
        System.out.println(art);
        Result<String> ret = new Result<>();
        if (cover_img != null) {
            String originalFilename = cover_img.getOriginalFilename();
            System.out.println(originalFilename);
            // 产生一个不重复的名字
            String uuidName = UUID.randomUUID().toString();
            // 取文件的后缀
//            String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 得到新文件名称
            String name = uuidName ;
            String dir = uuidName.substring(0, 3);
            String workDir = realPath + "imgdir/" + dir;
            File dirFile = new File(workDir);
            // 创建 子目录， 用来放文件
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            System.out.println(dir + "/" + name);
            File newFile = new File(workDir + "/" + name);
            cover_img.transferTo(newFile);
            ret.setData(dir + "/" + name);
        }
        ret.setStatus(0);
        ret.setMessage("success ");
        System.out.println(ret);
        return ret;
    }
}
